package cn.harmony.base.network;


import cn.harmony.base.util.StringUtil;
import cn.harmony.shf.MyApplication;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;



import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.InnerEvent;
import ohos.utils.net.Uri;
import okhttp3.Call;

/**
 * 执行网络数据的交互，提交请求数据并获取到服务器的反馈。
 *
 * @author Administrator
 * @date 2018-4-12
 */
public abstract class EndHandle {
    /**
     * 通常接口都会返回一个"0000"的status表示请求正常
     */
    public static final String STATUS_OK = "0000";
    /**
     * 当前联网操作
     */
    protected RequestCall requestCall;
    /**
     * 当前缓存的所有网络请求集合
     */
    protected ArrayList<WeakReference<RequestCall>> okNetlist = new ArrayList<WeakReference<RequestCall>>();
    private JSONObject jo;
    private final int isErr = 200;

    /**
     * 通过新线程执行网络请求
     *
     * @param requestMethod  HTTP连接方式，0=GET方式（默认）,1=PSOT方式,2=PUT方式。
     * @param url            请求地址
     * @param paramList      请求参数
     * @param netDataHandler 请求返回结果的处理器
     * @return RequestCall 网络请求
     */
    public RequestCall sendRequestRunnable(final int requestMethod,
                                           final String url, final List<BasicNameValuePair> paramList,
                                           final NetDataHandle netDataHandler) {
        netDataHandler.netBefore();
        try {
            requestCall = null;
            Map<String, String> params = HttpRequestUntil.getParams(paramList);
            Map<String, String> headers = HttpRequestUntil.getHttpHeader();
            switch (requestMethod) {
                case 1:

                    requestCall = OkHttpUtils.post().url(url).headers(headers).params(params).build();
                    break;
                case 2:
                    requestCall = OkHttpUtils.put().url(url).headers(headers).params(params).build();
                    break;
                default:
                    requestCall = OkHttpUtils.get().url(url).headers(headers).params(params).build();
                    break;
            }

            requestCall.execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                    if (netDataHandler != null) {
                        netDataHandler.noDataHanle();
                    }

                }

                @Override
                public void onResponse(String response, int id) {
                    if (netDataHandler != null) {
                        netDataHandler.netSuccessHanle(response);
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (requestCall != null && !requestCall.isCanceled() && netDataHandler != null) {
                netDataHandler.noDataHanle();
            }
        }
        if (requestCall != null && !requestCall.isCanceled()) {
            okNetlist.add(new WeakReference<RequestCall>(requestCall));
        }

        return requestCall;
    }

    /**
     * 取消当前的网络请求,通常按下返回键时，取消进度对话框时一同调用。
     *
     * @param mayInterruptIfRunning 这个参数目前没有用了，有时间去掉
     */
    public void cancel(boolean mayInterruptIfRunning) {
        if (requestCall != null) {
            requestCall.cancel();
        }
    }

    /**
     * 取消掉所有的通过本类建立的联网操作
     */
    public void cancelAll(boolean mayInterruptIfRunning) {
        if (okNetlist == null || okNetlist.size() <= 0) {
            return;
        }
        for (Iterator<WeakReference<RequestCall>> it = okNetlist.iterator(); it.hasNext(); ) {
            RequestCall requestCall2 = it.next().get();
            if (requestCall2 != null) {
                requestCall2.cancel();
                //试图取消对此任务的执行
            }
            it.remove();
        }
    }

    /**
     * 当前联网操作是否取消
     */
    public boolean isCancelled() {
        if (requestCall != null) {
            return requestCall.isCanceled();
        } else {
            return true;
        }
    }


    /**
     * 关闭进度对话框
     */
    public void dialogDismiss(EventHandler handler, String msg) {
        InnerEvent message =InnerEvent.get();
        message.eventId=2;
        message.object=msg;

        if (handler != null) {
            handler.distributeEvent(message);
        }
    }

    /**
     * 显示进度对话框
     */
    public void dialogShow(EventHandler handler, String msg) {
        InnerEvent message = InnerEvent.get();
        message.object = msg;
        message.eventId = 1;
        if (handler != null) {
            handler.distributeEvent(message);
        }
    }

    /**
     * 关闭进度对话框
     */
    public void dialogDismiss(EventHandler handler) {
        InnerEvent message = InnerEvent.get();
        message.object = "";
        message.eventId = 2;
        if (handler != null) {
            handler.distributeEvent(message);
        }
    }

    /**
     * 显示进度对话框
     */
    public void dialogShow(EventHandler handler) {
        InnerEvent message = InnerEvent.get();
        message.object = "";
        message.eventId = 1;
        if (handler != null) {
            handler.distributeEvent(message);
        }
    }

    /**
     * 网络堵塞提示
     */
    public void toastNetError() {
        // "请检查网络配置，也可以拨打客服电话咨询！",
//		 MyApplication.toast("网络堵塞");
    }


    /**
     * 服务器返回简单的消息处理，当成功是包含key:"message","success"。失败提示key："message","key"，
     * 详细见代码处理 。
     *
     * @param handler     UI交互控制器
     * @param json        返回json
     * @param successWhat UI成功的处理handler.sendEmptyMessage(what);中的what。
     * @param failWhat    UI失败的处理handler.sendEmptyMessage(what);中的what。
     */
    protected void commitMessageHanler(final EventHandler handler, String json,
                                       int successWhat, int failWhat) {
        String message = "";
        try {
            JSONObject jo = new JSONObject(json);
            message = jo.getString("message");

            String success = jo.getString("success");
            if ("true".equalsIgnoreCase(success)) {
                InnerEvent obtain = InnerEvent.get();
                obtain.eventId = successWhat;
                obtain.object = message;
                handler.distributeEvent(obtain);
            } else {
                failMessageHanle(handler, json, failWhat);
            }
            failMessageHanle(handler, json, failWhat);
        } catch (JSONException e) {
            failMessageHanle(handler, json, failWhat);
        }
    }

    /**
     * 服务器返回的失败消息处理，失败提示key："message","key"， 详细见代码处理 。
     * 如果从json中无法提取message信息，会返回json原文
     *
     * @param handler  UI交互控制器
     * @param json     返回json
     * @param failWhat UI失败的处理handler.sendEmptyMessage(what);中的what。
     * @return
     */
    public String failMessageHanle(final EventHandler handler, String json,
                                   int failWhat) {
        String message = null;
        try {
            JSONArray jsonArray = new JSONArray(json);
            String mMessage = "";
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                jsonObject.getString("key");
                mMessage += jsonObject.getString("message") + "";
            }
            message = mMessage;
        } catch (Exception e2) {

        } finally {
            if (StringUtil.isEmpty(message)) {
                message = json;
            }
            InnerEvent obtain = InnerEvent.get();
            obtain.object = message;
            obtain.eventId = failWhat;
            handler.distributeEvent(obtain);
        }
        return message;
    }

    /**
     * 拼接请求参数
     *
     * @param url
     * @param params
     * @return
     */
    protected String appendParams(String url, Map<String, String> params) {
        if (url == null || params == null || params.isEmpty()) {
            return url;
        }

        Uri.Builder builder = Uri.parse(url).makeBuilder();
        Set<String> keys = params.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            builder.appendDecodedQueryParam(key, params.get(key));
        }
        return builder.build().toString();
    }
}
